package org.jeecg.modules.xl.kuaidi100.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.api.Subscribe;
import com.kuaidi100.sdk.contant.ApiInfoConstant;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.*;
import com.kuaidi100.sdk.response.*;
import com.kuaidi100.sdk.utils.SignUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.shiro.IgnoreAuth;
import org.jeecg.modules.xl.kuaidi100.entity.XlKuaidi100Logitrace;
import org.jeecg.modules.xl.kuaidi100.service.IXlKuaidi100LogitraceService;
import org.jeecg.modules.xl.logicmana.entity.XlCustomerLogisticPackage;
import org.jeecg.modules.xl.logicmana.service.IXlCustomerLogisticPackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 快递100controller
 *
 * @author deco
 * @create 2024-10-28
 */

@RestController
@RequestMapping("/xl/kd100")
@Slf4j
public class Kuaidi100Controller {

    String key = "apCDGXjp8152";
    String customer = "3E163C1F545E1D6C38EC8DABE13293B3";
    String secret ="c28bd653d6bc405288bb31ffe799e741";
    String userid =  "c28bd653d6bc405288bb31ffe799e741";


    @Autowired
    private IXlKuaidi100LogitraceService logitraceService;

    /**
     *
     * @param comp 物流公司编码，必填
     * @param logisticorder 快递单号，必填
     * @param phone 收、寄件人 号码，非必填
     */
    @ApiOperation(value="物流信息查询", notes="物流信息查询")
    @GetMapping(value = "/queryTrack")
//    @IgnoreAuth
    public Result<List<QueryTrackData>> queryTrack(String comp, String logisticorder , String phone,String orderCode) throws Exception {
        return logitraceService.queryTrack(comp,logisticorder,phone,orderCode);
    }


    /**
     * 订阅接口
     */
    @RequestMapping("subscribe")
    public void testSubscribe() throws Exception{
        SubscribeParameters subscribeParameters = new SubscribeParameters();
        //平接回调接口
        String baseUrl =  "http://slt.bugless.site:18930";
        subscribeParameters.setCallbackurl(baseUrl+"/jeecg-boot/xl/kd100/kuaidi100callBack");
        subscribeParameters.setResultv2("4");
        SubscribeParam subscribeParam = new SubscribeParam();
        subscribeParam.setParameters(subscribeParameters);
        subscribeParam.setCompany("zhongtongkuaiyun");
        subscribeParam.setNumber("301131798944");
        subscribeParam.setKey(key);

        SubscribeReq subscribeReq = new SubscribeReq();
        subscribeReq.setSchema(ApiInfoConstant.SUBSCRIBE_SCHEMA);
        subscribeReq.setParam(new Gson().toJson(subscribeParam));

        IBaseClient subscribe = new Subscribe();
        System.out.println(subscribe.execute(subscribeReq));
    }

    /**
     * 订阅推送处理(参照)
     * 订阅成功后，如果该快递单号有轨迹（包括已经签收的单），快递100将会在15分钟-4个小时推送；后面将会4个小时跟踪一次，跟踪到有轨迹变化则推送；
     * 如果订阅成功后，3天查无结果（录错单/快递公司错了/揽收比较晚），快递100将会推送3天查无结果，可以继续重新订阅。
     *
     * 回调接口支持自定义参数,比如订阅时回调地址填写的是 http://www.xxx.com?orderId=1233333
     * 可以通过下面这种方式获取到orderId： String orderId = request.getParameter("orderId");
     *
     * 返回值必须是下面这样的格式，否则快递100将认为该推送失败，快递100将会重试3次该推送，时间间隔35分钟；
     * 成功结果返回例子： {"result":true,"returnCode":"200","message":"提交成功"}
     *
     * @param request
     * @return: com.kuaidi100.sdk.response.SubscribeResp
     * @author: api.kuaidi100.com
     * @time: 2020/7/16 19:48
     */

    @IgnoreAuth
    @PostMapping("kuaidi100callBack")
    public SubscribeResp callBackUrl(HttpServletRequest request){
        String param = request.getParameter("param");
        String sign = request.getParameter("sign");
        //建议记录一下这个回调的内容，方便出问题后双方排查问题
        log.debug("快递100订阅推送回调结果|{}|{}",param,sign);
        //订阅时传的salt,没有可以忽略
        String salt = "";
        String ourSign = SignUtils.sign(param + salt);
        sign = ourSign;
        SubscribeResp subscribeResp = new SubscribeResp();
        subscribeResp.setResult(Boolean.TRUE);
        subscribeResp.setReturnCode("200");
        subscribeResp.setMessage("成功");
        //加密如果相等，属于快递100推送；否则可以忽略掉当前请求
        if (ourSign.equals(sign)){
            SubscribePushParamResp subscribePushParamResp = new Gson().fromJson(param, SubscribePushParamResp.class);
            List<SubscribePushData> list = subscribePushParamResp.getLastResult().getData();
            for(SubscribePushData queryTrackData :list ){
                XlKuaidi100Logitrace  tracetemp = new XlKuaidi100Logitrace();
                tracetemp.setLogiCode(subscribePushParamResp.getLastResult().getNu());
                tracetemp.setLogiComCode(subscribePushParamResp.getLastResult().getCom());
                tracetemp.setStatuscode(queryTrackData.getStatusCode());
                tracetemp.setStatus(queryTrackData.getStatus());
                tracetemp.setTime(queryTrackData.getTime());
                tracetemp.setFtime(queryTrackData.getFtime());
                tracetemp.setContext(queryTrackData.getContext());
                logitraceService.saveOrUpdate(tracetemp);
            }
            return subscribeResp;
        }
        return null;
    }

}

